<template>
  <basic-container class="app-container-delivery">
    <div class="maindelivery" v-show="showdelivery">
      <div class="delivery-container">
        <el-form ref="form" :model="deliveryFrom" label-width="80px">
          <div class="flexmaindelivery">
            <el-form-item label="后台单号:">
              <el-input v-model.trim="deliveryFrom.xmbzNo" placeholder="请输入后台单号" clearable style="width: 150px;" class="filter-item" size="small" @keyup.enter.native="handleFilter(Launchdate)" />
            </el-form-item>
            <!--  <el-form-item label="平台单号:">
              <el-input v-model.trim="deliveryFrom.platformOrderId" placeholder="请输入平台单号" clearable style="width: 150px;"
                class="filter-item" size="small" @keyup.enter.native="handleFilter" />
            </el-form-item> -->
            <el-form-item label="配送时间:">
              <el-date-picker size='small' v-model="Launchdate" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :clearable="false" align="right">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="地区:">
              <el-select ref="mainWarehouseRef" v-model="mainWarehouseNames" placeholder="请选择地区" style="width: 120px;" class="filter-item" size="small" @change="getmainWarehouseIds" @keydown.native="selectBlur($event)">
                <el-option v-for="item in mainWarehousesList" :key="item.id" :label="item.deptName" :value="{label:item.deptName,value:item.id}" />
              </el-select>
            </el-form-item>
          <el-form-item label="是否跳舞:">
            <DanceTypeSelect v-model="deliveryFrom.isDance" size="small" clearable></DanceTypeSelect>
          </el-form-item>
          <el-form-item label="商品类型" style="margin-bottom: 15px!important;">
            <CategoryTreeSelect v-model="deliveryFrom.addedServices" size="small" clearable change-on-select></CategoryTreeSelect>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter(Launchdate)" style="margin-right: 10px;" plain>查询</el-button>
          </el-form-item>
          <div class="mb-20">
            <el-checkbox v-model="clickFramingchecked" border="" size="small" @change='clickFraming'>
              开启自动刷单
            </el-checkbox>
            <el-badge :value="this.abnormatotal" :hidden="this.abnormatotal == 0" :max="99" class="item">
              <el-button class="filter-item" size="small" @click="HandledeliveryAbnormal">配送异常列表</el-button>
            </el-badge>
            <addedServiceNotice class="ml-20 d-ib"></addedServiceNotice>
            <transferOvertimeNotice class="ml-20 d-ib"></transferOvertimeNotice>
            <consultWorkorderNotice class="ml-20 d-ib" v-xmbz-permission="'delivery_seek_order_tip'"></consultWorkorderNotice>
          </div>
          </div>
        </el-form>
      </div>
      <div class="Distribution">
        <div class="Distribution-item" v-for="(item,index) in DistributionList" :key="index" @click="handleTabs(index,item)" :class="{active:(indexs==index)}">
          <div class="Warehouse">{{item.name}}</div>
          <div class="deliveryData">
            <div class="Unassigned">
              <div class="names">未分配</div>
              <div class="name">已分配</div>
            </div>
            <div class="allocated">
              <div :class="{'c-red fw-bold': item.notDelivery != 0}">{{item.notDelivery}}</div>
              <div>{{item.deliveried}}</div>
            </div>
          </div>
        </div>

      </div>
      <div class="DistributionTable">
        <div class="unassignedList" v-if="Unassigned==1">
          <div class="tag">
            <img :src="role" alt="">
            <div class="ordernum" style="margin-right: 20px;">
              <span class="order-quantity">未分配   {{(DistributionTableList && DistributionTableList.length) || 0}}单</span>
            </div>
            <el-button size="mini" type="primary" plain @click="handleModifydeliverysUn" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">
              选择配送员</el-button>
            <el-button size="mini" type="primary" plain @click="showTable = !showTable">{{showTable ? '收起列表' : '展开列表'}}</el-button>
          </div>
          <transition name="fade">
          <el-table :data="DistributionTableList" style="width: 100%" ref="multipleTableNo" @select='clearOtherNo(DistributionTableList)' @select-all='clearOtherNo(DistributionTableList)' @selection-change="handleSelectionChangeNo" v-show="showTable">
            <el-table-column type="selection" style="width: 5%" prop="id"></el-table-column>
            <el-table-column fixed prop="xmbzNo" label="后台单号" align="center" width="100"></el-table-column>
            <!--    <el-table-column fixed prop="platformOrderId" label="平台单号" align="center" style="width: 10%"></el-table-column> -->
            <el-table-column prop="deliveryTime" label="配送时间" width="150" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" align="center" width="100"></el-table-column>
            <el-table-column prop="printingState" label="打印状态" align="center" width="100">
              <template slot-scope="{row}">
                <span v-if='row.printingState==1'>未打印</span>
                <span v-if='row.printingState==2'>已打印</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" align="center">
              <template slot-scope="{row}">
                <p v-for="(detail, index) in row.orderDetailVOS" :key="index">
                  <span>{{detail.goodsName}}</span>
                  <span style="color: #f56c6c">({{ detail.goodsSpecs }}，{{ detail.num }})</span>
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="deliveryRemark" label="配送备注" align="center"></el-table-column>
            <!-- <el-table-column label="是否跳舞" prop="isDance" width="100" align="center">
              <template slot-scope="{row}">
                <span>{{ danceLabelMap[row.isDance] || '-' }}</span>
              </template>
            </el-table-column> -->
            <el-table-column prop="receiverAddress" label="配送地址" style="width: 45%" align="center"></el-table-column>
            <el-table-column prop="tyingRefundNotReturn" label="搭售退单说明" align="center">
              <template slot-scope="scope">
                <el-tag type="warning" v-if="scope.row.tyingRefundNotReturn">{{ scope.row.tyingRefundNotReturn }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleWatchOrder(scope.row)" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">查看订单</el-button>
              </template>
            </el-table-column>
          </el-table>
          </transition>
        </div>
        <div class="assigning" v-if="assigning==2" v-for="(item,index) in AssigningData" :key='index'>
          <div class="tag">
            <img :src="role" alt="">
            <div class="ordernum">
              <span class="delivery">{{item.delivery}} &nbsp;&nbsp;&nbsp;&nbsp;{{item.total}}单 &nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span class="order-quantity">配送中：{{item.deliveryCount}}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span class="order-signfor">已签收：{{item.receivedCount}}&nbsp;&nbsp;</span>
            </div>
            <el-button size="mini" type="success" plain @click="handleAllSetOutOrder(item)" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">
              配送出发</el-button>
            <el-button size="mini" type="primary" plain @click="handleModifydeliverys(item)" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">
              修改配送员</el-button>
          </div>
          <transition name="fade">
          <el-table :ref="'multipleTable' + item.id" :data="item.list" style="width: 100%" @select='clearOther(item)' @select-all='clearOther(item)' @selection-change="handleSelectionChange" v-show="showTable">
            <el-table-column type="selection" width="44" prop="id" style="width: 5%"></el-table-column>
            <el-table-column fixed prop="xmbzNo" label="后台订单" align="center" width="100"></el-table-column>
            <!--          <el-table-column fixed prop="platformOrderId" label="平台单号" align="center" style="width: 10%"></el-table-column> -->
            <el-table-column prop="deliveryTime" label="配送时间" width="150" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center"></el-table-column>
            <!-- <el-table-column prop="goodsName" label="商品名称" align="center" style="width: 25%" :show-overflow-tooltip="true"></el-table-column> -->
            <el-table-column prop="printingState" label="打印状态" width="100" align="center" :show-overflow-tooltip="true">
              <template slot-scope="{row}">
                <span v-if='row.printingState==1'>未打印</span>
                <span v-if='row.printingState==2'>已打印</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="商品名称" align="center">
              <template slot-scope="{row}">
                <p v-for="(detail, index) in row.orderDetailVOS" :key="index">
                  <span>{{detail.goodsName}}</span>
                  <span style="color: #f56c6c">({{ detail.goodsSpecs }}，{{ detail.num }})</span>
                </p>
              </template>
            </el-table-column>
            <el-table-column prop="deliveryRemark" label="配送备注" align="center"></el-table-column>
            <!-- <el-table-column label="是否跳舞" prop="isDance" width="100" align="center">
              <template slot-scope="{row}">
                <span>{{ danceLabelMap[row.isDance] || '-' }}</span>
              </template>
            </el-table-column> -->
            <el-table-column prop="receiverAddress" label="配送地址" style="width: 45%" align="center"></el-table-column>
            <el-table-column prop="tyingRefundNotReturn" label="搭售退单说明" align="center">
              <template slot-scope="scope">
                <el-tag type="warning" v-if="scope.row.tyingRefundNotReturn">{{ scope.row.tyingRefundNotReturn }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="220">
              <template slot-scope="{row}">
                <el-button size="mini" type="success" plain @click="handleSetOutOrder(row)" v-if="row.deliverySetOut=='1'">
                  配送出发</el-button>
                <el-button size="mini" @click="handleWatchOrder(row)" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">查看订单</el-button>
              </template>
            </el-table-column>
          </el-table>
          </transition>
        </div>
      </div>
    </div>
    <div class="showabnormal" v-show="showabnormal">
      <div class="tab">
        <div class="tab-item" @click="backabnormal">配送分配</div>
        <div class="tab-item act">/配送异常列表/</div>
      </div>
      <div class="fifterabnormal">
        <el-form ref="form" :model="abnormalFrom" label-width="80px">
          <div class="flexmaindelivery">
            <el-form-item label="后台单号:">
              <el-input v-model.trim="abnormalFrom.xmbzNo" placeholder="请输入后台订单" style="width: 150px;" class="filter-item" size="small" />
            </el-form-item>
            <el-form-item label="配送员:">
              <el-input v-model.trim="abnormalFrom.delivery" placeholder="请输入配送员" style="width: 150px;" class="filter-item" size="small" />
            </el-form-item>

            <el-form-item label="">
              <el-date-picker v-model="timeValue" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" size="medium" align="right"></el-date-picker>
            </el-form-item>
            <el-form-item width="300px">
              <div class="flexmaindelivery">
                <el-button type="primary" class="filter-item" icon="el-icon-search" size="small" @click="handleabnormalFilter">查询</el-button>
                <el-button type="success" class="filter-item" icon="el-icon-download" size="small" @click="exportAbnormal">导出</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="abnormaList" v-for="(item,index) in abnormalList" :key="index" v-if='abnormalList&&abnormalList.length>0'>
        <div class='line'>
          <div class='xmbzNo'> <span>后台单号:</span>
            {{item.xmbzNo}}</div>
          <div class="count">第{{item.count}}次异常</div>
        </div>
        <div class="abnormaList-item">
          <div class="flexabnorma">
            <p style="width:30%">
              <em>平台单号:</em>
              {{item.platformOrderId}}
            </p>
            <p style="width:30%">
              <em>配送员:</em>
              {{item.delivery}}
            </p>

            <p>
              <em>地区:</em>
              {{item.mainWarehouse}}
            </p>
            <p>
              <em>分仓:</em>
              {{item.branchWarehouse}}
            </p>
          </div>
          <div class="flexabnorma">
            <em>配送时间:</em>
            {{item.deliveryTime}}
          </div>
          <div class="flexabnorma">
            <em>配送地址:</em>
            {{item.receiverAddress}}
          </div>
          <div class="flexabnorma">
            <em>异常内容:</em>
            {{item.message}}
          </div>

        </div>
        <div class="deliveryflex">
          <el-button class="filter-item" size="small" @click="logs(item)">日志</el-button>
          <el-button class="filter-item" v-if="item.dayDiff<2" size="small" @click="handleturndown(item)">驳回</el-button>
          <el-button type="primary" v-if="item.dayDiff<2" class="filter-item" size="small" @click="handleTransferpre(item)">转给客服</el-button>
          <el-button type="primary" v-if="item.dayDiff<2" class="filter-item" size="small" @click="handleModifydelivery(item)">修改配送员</el-button>
          <span v-if="item.dayDiff>1">已完结</span>
        </div>
      </div>
      <div class="abnormaListno" v-if='abnormalList.length<=0'>
        <span>暂无配送异常数据</span>
      </div>
      <pagination v-show="abnormatotal>0" :total="abnormatotal" :page.sync="abnormalFrom.page" :limit.sync="abnormalFrom.size" @pagination="getabnormalList" />
    </div>
    <el-dialog title="我的配送订单查看" :visible.sync="dialogorderdetail">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="订单信息" name="first">
          <div class="orderInfo">
            <div class="orderInfo-item">
              <span class="name">后台订单：</span>
              <span>{{orderInfoList.xmbzNo}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">平台订单：</span>
              <span>{{orderInfoList.platformOrderId}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">分仓：</span>
              <span>{{orderInfoList.receiverAddress}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">收货人：</span>
              <span>{{orderInfoList.receiverName}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">收货电话：</span>
              <!-- <span>{{orderInfoList.receiverPhone}}</span> -->
              <viewReceiverPhone :orderInfo="orderInfoList" ref="viewReceiverPhone"></viewReceiverPhone>
            </div>
            <div class="orderInfo-item">
              <span class="name">配送时间：</span>
              <span>{{orderInfoList.deliveryStartTime}}~{{orderInfoList.deliveryEndTime}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">配送备注：</span>
              <span>{{orderInfoList.deliveryNotes}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">客户备注：</span>
              <span>{{orderInfoList.customerNotes}}</span>
            </div>
            <div class="orderInfo-item">
              <span class="name">客服备注：</span>
              <span>{{orderInfoList.customerServiceNotes}}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品信息" name="second">
          <div class="goodInfo">
            <div class="goodInfomain" v-for="(child,index2) in goodInfoData" :key="index2">
              <div class="goodInfo-item">
                <span class="name">蛋糕：</span>
                <span>{{child.goodsName}}</span>
              </div>
              <div class="goodInfo-item">
                <span class="name">价格：</span>
                <span v-if="child.totalPrice">{{child.totalPrice/100}}</span>
              </div>
              <div class="goodInfo-item">
                <span class="name">规格：</span>
                <span>{{child.goodsSpecs}}</span>
              </div>
              <div class="goodInfo-item">
                <span class="name">数量：</span>
                <span>{{child.num}}</span>
              </div>
              <div class="goodInfo-item">
                <span class="name">状态：</span>
                <span>{{child.productionStateName}}</span>
              </div>
              <div class="goodInfo-item">
                <span class="name">祝福语：</span>
                <span>{{child.blessings}}</span>
              </div>
            </div>
            <div class="goodInfototal">
              所选蛋糕总计:
              <span>{{goodInfototal}}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="配送地址" name="third">
          <div class="map">
            <div class="">
              <p>
                <span class="order-messageing">配送地址：</span>
                <span>{{ orderInfoList.receiverAddress }}</span>
              </p>
            </div>
            <XmMap ref="xmMap" style="width: 100%;height: 400px"></XmMap>
          </div>
        </el-tab-pane>
        <el-tab-pane label="订单日志" name="fourth" style="min-height: 500px;">
          <div class="radio" style="margin-bottom: 20px;font-size: 15px;">
            显示方式：
            <el-radio-group v-model="reverse">
              <el-radio :label="true">倒序</el-radio>
              <el-radio :label="false">正序</el-radio>
            </el-radio-group>
          </div>
          <el-timeline :reverse="reverse">
            <el-timeline-item v-for="(item,index) in activities" :key="index" placement="top" style="font-size: 15px;">
              <el-card style="box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);width: 90%;">
                <h4 style="margin-left: 8px;">{{ item.operator }}</h4>
                <h4 v-html='item.action'>{{item.action}}</h4>
                <p style="margin-left: 8px;color: #5e6d82;">{{item.updateTime}}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
        <!-- <el-tab-pane label="订单日志" name="fourth"> -->

        <!-- <el-timeline style="padding-top: 10px;">
            <el-timeline-item v-for="(item,index) in activities" :key="index" placement="top" style="font-size: 15px;">
              <el-card style="box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);width: 90%;">
                <h4 style="margin-left: 8px;">{{ item.operator }}</h4>
                <h4 v-html='item.action'>{{item.action}}</h4>
                <p style="margin-left: 8px;color: #5e6d82;">{{item.updateTime}}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane> -->
      </el-tabs>
    </el-dialog>
    <el-dialog title="驳回" :visible.sync="dialogturndownVisible" center>
      <el-form :model="turndownform" ref="turndownform" :rules="rules">
        <el-form-item label="驳回理由" label-width="120px" prop="reason">
          <el-input type="textarea" maxlength="50" show-word-limit v-model="turndownform.reason" :autosize="{ minRows: 6, maxRows:8}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogturndownVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitturndownform('turndownform')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="转给客服" :visible.sync="dialoghandleReturnferVisible" center>
      <el-form :model="turndownform" ref="turndownform" :rules="rules">
        <el-form-item label="内容" label-width="120px" prop="reason">
          <el-input type="textarea" maxlength="50" show-word-limit v-model="turndownform.reason" :autosize="{ minRows: 6, maxRows:8}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialoghandleReturnferVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleTransfer()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 异常配送列表 -->
    <el-dialog title="修改配送员" :visible.sync="dialogDistributorVisible" width="width" lock-scroll>
      <el-button type="warning" plain size="small" style='margin-bottom: 10px;' v-model="delivery" @click='handledeliverys(deliveriesList)'>清空选中</el-button>
      <div v-for="(itemmain, key, index) in deliveriesList" :key="index" style="width: 100%;" class="deliveriesList">
        <div class="deliveryperson">{{ key }}</div>
        <div class="delivery-item">
          <span v-for="item in itemmain" :key="item.index" :class="{'active': item.isSelected== 1}" @click="handledistror(item,deliveriesList)">{{ item.name }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="saveflag">
        <el-button type="primary" @click="handelsaveOrdernoraml" :loading="distributing">保存</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button @click="dialogDistributorVisible = false">取 消</el-button>
        <el-button type="primary" @click="handelDistributeDeliveryForOrder(deliveriesList)" :loading="distributing">分配</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改配送员" :visible.sync="dialogDistributorVisibles" width="width" lock-scroll>
      <el-button type="warning" plain size="small" style='margin-bottom: 10px;' v-model="delivery" @click='handledeliverys(deliveriesList)'>清空选中</el-button>
      <div v-for="(itemmain, key, index) in deliveriesList" :key="index" style="width: 100%;" class="deliveriesList">
        <div class="deliveryperson">{{ key }}</div>
        <div class="delivery-item">
          <span v-for="item in itemmain" :key="item.index" :class="{'active': item.isSelected== 1}" @click="handledistror(item,deliveriesList)">{{ item.name }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="saveflag">
        <el-button type="primary" @click="handelsaveOrder" :loading="distributing">保存</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button @click="dialogDistributorVisibles = false">取 消</el-button>
        <el-button type="primary" @click="handelDistributeDeliveryOrder(deliveriesList)" :loading="distributing">分配</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改配送员" :visible.sync="dialogDistributorVisibleno" width="width" lock-scroll>
      <el-button type="warning" plain size="small" style='margin-bottom: 10px;' v-model="delivery" @click='handledeliverys(deliveriesList)'>清空选中</el-button>
      <div v-for="(itemmain, key, index) in deliveriesList" :key="index" style="width: 100%;" class="deliveriesList">
        <div class="deliveryperson">{{ key }}</div>
        <div class="delivery-item">
          <span v-for="item in itemmain" :key="item.index" :class="{'active': item.isSelected== 1}" @click="handledistror(item,deliveriesList)">{{ item.name }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="saveflag">
        <el-button type="primary" @click="handelsaveOrderno" :loading="distributing">保存</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button @click="dialogDistributorVisibleno = false">取 消</el-button>
        <el-button type="primary" @click="handelDistributeDeliveryOrderno(deliveriesList)" :loading="distributing">分配</el-button>
      </span>
    </el-dialog>
    <el-dialog title="日志" :visible.sync="LogFormVisible" width="width:400px">
      <div class="radio">显示方式：
        <el-radio-group v-model="reverse">
          <el-radio :label="true">倒序</el-radio>
          <el-radio :label="false">正序</el-radio>
        </el-radio-group>
      </div>
      <el-timeline :reverse="reverse">
        <el-timeline-item v-for="(activity, index) in LogList" :key="index" :icon="activity.icon" :type="activity.type" :color="activity.color" :size="activity.size" :timestamp="activity.createTime">
          <h5>{{activity.operator}}</h5>
          <h4 v-html="activity.action">{{activity.action}}</h4>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </basic-container>
</template>
<script>
import {
  getorderNotDeliveryInfos, //获取配送分配页面未分配列表
  getMainWarehouseListAll,
  getdeliveriesList,
  getOrderInfo, //订单信息
  getOrderGoodsInfo, //商品信息
  getEveryAreaDeliveryNum, //获取配送分配页面总仓和分仓的数据
  getUnassignedlist, //未分配列表
  distributeDeliveryForOrderDispatch,
  getOrderOperateLog, // 日志
  getOrderDeliveryInfoByDelivery, //获取配送分配页面配送员的订单列表
  deliverySetOutOrder,
  getOrderDeliveryAbnormalList, //配送异常列表
  turnWorkOrderDeliveryAbnormal, // 配送异常订单转给客服
  rejectOrderDeliveryAbnormal, //驳回配送异常订单
  modifyOrderDeliveryAbnormal, // 修改配送异常订单的配送员

} from "@/api/orderDispatch"
import role from "@/assets/image/role.png"
import Pagination from "@/components/Pagination" // secondary package based on el-pagination
import { danceLabelMap } from '@/const'
import addedServiceNotice from './addedServiceNotice'
import transferOvertimeNotice from './transferOvertimeNotice'
import consultWorkorderNotice from './consultWorkorderNotice'
import viewReceiverPhone from "@/components/order/orderInfoDialog/viewReceiverPhone"

export default {
  components: {
    Pagination,
    addedServiceNotice,
    transferOvertimeNotice,
    consultWorkorderNotice,
    viewReceiverPhone
},
  data () {
    return {
      LogFormVisible: false,
      LogList: [], //日志表
      dialoghandleReturnferVisible: false,  // 控制转给客服弹窗
      showdelivery: true,
      showabnormal: false,
      reverse: false,
      role, //头像
      total: 2,
      deliveryFrom: {
        deptId: '',
        xmbzNo: "", // 订单号
        platformOrderId: '', //平台单号
        // mainWarehouse: "", //地区
        totalWarehouseId: '',
        warehouseId: "", //分仓
        deliveryStartTime: this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 00:00:00")
          .toString(), //配送开始时间
        deliveryEndTime: this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 23:59:59")
          .toString(), //配送结束时间
        delivery: '',
        page: 1,
        size: 10,
        isDance: ''
      },

      clickFramingchecked: false,
      mainWarehousesList: [],
      mainWarehouseIds: "",
      mainWarehouseNames: "全部",

      Launchdate: [
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 23:59:59")
          .toString(),
      ],
      pickerOptions: {
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime()
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            const day1 = 31 * 24 * 3600 * 1000
            let maxTime = this.pickerMinDate + day1
            let minTime = this.pickerMinDate - day1
            return time.getTime() > maxTime || time.getTime() < minTime
          }
        }
      },
      DistributionList: [],
      indexs: 0,
      assigning: 2,
      Unassigned: 1,
      //列表数据
      DistributionTableList: [],
      AssigningList: [], //分配
      AssigningData: [],
      // 查看订单
      dialogorderdetail: false,
      listdetails: [],
      activeName: "first", //生产详情显示状态
      orderInfoList: [], //订单信息
      goodInfoData: [],
      abnormalList: [], //异常列表
      abnormalFrom: {
        deptId: this.cityareaId || 1,
        xmbzNo: "", // 订单号
        platformOrderId: '', //平台单号
        delivery: "", //配送员
        deliveryStartTime: "",
        deliveryEndTime: "",
        page: 1,
        size: 10
      },
      abnormatotal: 0,
      turndownform: {
        reason: "" //理由
      },
      cityareaId: '', //
      rules: {
        reason: [{
          required: true,
          message: "请填写驳回理由",
          trigger: "blur"
        }]
      },
      chooseDance: [
        {
            name: "跳舞",
            status: 1
        },
        {
            name: "不跳舞",
            status: 0
        },
        {
            name: "不确定",
            status: 2
        }
    ],
      dialogturndownVisible: false,
      goodInfototal: "", //商品信息价格
      // 配送员
      dialogDistributorVisible: false,
      dialogDistributorVisibles: false,
      dialogDistributorVisibleno: false,
      deliveriesList: [],
      activeIndex: 0,
      activities: [],
      multipleSelections: {},
      multipleSelection: [],
      multipleSelectionNo: [],
      rejectOrderDeliveryAbnormalId: '', // 驳回ID
      deliveriesId: '', //配送员ID
      delivery: '',
      saveflag: false,
      RowSelectionFlag: true,
      checked: false,
      distributing: false,
      NameFlag: false,
      timeValue: [
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
        this.dayjs(
          new Date()
        )
          .format("YYYY-MM-DD 23:59:59")
          .toString(),
      ],
      danceLabelMap,
      whetherToDance: [ {},],
      showTable: true
    }
  },
  watch: {
    'dialogorderdetail' () {
      if (this.dialogorderdetail) {
        window.removeEventListener("keydown", this.keyupEnter)
      } else {
        window.addEventListener("keydown", this.keyupEnter)
      }
    },
    'dialogDistributorVisibleno' () {
      if (this.dialogDistributorVisibleno) {
        window.removeEventListener("keydown", this.keyupEnter)
      } else {
        window.addEventListener("keydown", this.keyupEnter)
      }
    },
    'dialogDistributorVisible' () {
      if (this.dialogDistributorVisible) {
        window.removeEventListener("keydown", this.keyupEnter)
      } else {
        window.addEventListener("keydown", this.keyupEnter)
      }
    },
    'dialogDistributorVisibles' () {
      if (this.dialogDistributorVisibles) {
        window.removeEventListener("keydown", this.keyupEnter)
      } else {
        window.addEventListener("keydown", this.keyupEnter)
      }
    },
  },
  mounted () {
    var saberareaIds = JSON.parse(localStorage.getItem('saber-areaId'))
    this.cityareaId = saberareaIds['content']
    this.mainWarehouse()
    setTimeout(() => {
      this.loadData()
      this.getabnormalList()
    }, 0.5 * 1000)
    window.addEventListener("keydown", this.keyupEnter)
  },
  destroyed () {
    window.removeEventListener("keydown", this.keyDown, false)
  },
  methods: {
    // 导出异常配送
    exportAbnormal () {
      if (this.timeValue && this.timeValue.length) {
        let deliveryStartTime = this.timeValue[0] + ":00"
        let deliveryEndTime = this.timeValue[1] + ":59"
        let deptId = this.cityareaId
        let user = JSON.parse(localStorage.getItem('saber-userInfo'))
        window.open(
          `/api/xmbz-order/orderDispatch/exportAbnormal?deptId=${deptId}&deliveryStartTime=${deliveryStartTime}&deliveryEndTime=${deliveryEndTime}&blade-auth=bearer ${user['content'].accessToken}`
        )
      } else {
        this.$message({
          showClose: true,
          message: "请选择时间",
          type: "warning",
        })
      }
    },
    logs (item) {
      //异常日志
      this.LogFormVisible = true
      getOrderOperateLog({
        orderId: item.orderId
      }).then(response => {
        this.LogList = response.data.data
      })
    },
    selectBlur (e) {
      if (e.keyCode == 13) {
        this.$refs['mainWarehouseRef'].blur()
        e.returnValue = false
      }
    },
    // 列表数据------------------------------------------------------------------------------------------------------
    keyupEnter () {
      if (window.event.keyCode == 13) {
        this.handleFilter(this.Launchdate) // 查询事件
      }
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated () {
      window.addEventListener("keydown", this.keyupEnter)
    },
    deactivated () {
      window.removeEventListener("keydown", this.keyupEnter)
    },
    loadData() {
      this.getList()
      this.getEveryAreaDeliveryNumList()
      this.getAssigningList()
    },
    getList () { //未分配列表
      getorderNotDeliveryInfos(this.getOrderNotDeliveryInfoParams()).then(response => {
        this.DistributionTableList = response.data.data.list
      })
    },
    getOrderNotDeliveryInfoParams() {
      const params = {
        deptId: this.cityareaId,
        xmbzNo: this.deliveryFrom.xmbzNo, // 订单号
        isDance: this.deliveryFrom.isDance, // 是否跳舞
        platformOrderId: this.deliveryFrom.platformOrderId, //平台单号：
        totalWarehouseId: this.deliveryFrom.totalWarehouseId, //地区
        warehouseId: this.deliveryFrom.warehouseId, //分仓
        deliveryStartTime: this.dayjs(this.Launchdate[0]).format("YYYY-MM-DD HH:mm:00"), //配送开始时间
        deliveryEndTime: this.dayjs(this.Launchdate[1]).format("YYYY-MM-DD HH:mm:59"), //配送结束时间
        addedServices: this.getAddedServicesStr(),
        delivery: false,
      }
      return params
    },
    getEveryAreaDeliveryNumParams() {
      return {
        deptId: this.cityareaId,
        mainWarehouseId: this.mainWarehouseIds,
        isDance: this.deliveryFrom.isDance, // 是否跳舞
        deliveryStartTime: this.dayjs(this.Launchdate[0]).format("YYYY-MM-DD HH:mm:00"),
        deliveryEndTime: this.dayjs(this.Launchdate[1]).format("YYYY-MM-DD HH:mm:59"),
        addedServices: this.getAddedServicesStr(),
      }
    },
    getOrderDeliveryInfoByDeliveryParams() {
      return {
        deptId: this.cityareaId,
        xmbzNo: this.deliveryFrom.xmbzNo, // 订单号
        isDance: this.deliveryFrom.isDance, // 是否跳舞
        platformOrderId: this.deliveryFrom.platformOrderId, //平台单号
        totalWarehouseId: this.deliveryFrom.totalWarehouseId, //地区
        warehouseId: this.deliveryFrom.warehouseId, //分仓
        deliveryStartTime: this.dayjs(this.Launchdate[0]).format("YYYY-MM-DD HH:mm:00"), //配送开始时间
        deliveryEndTime: this.dayjs(this.Launchdate[1]).format("YYYY-MM-DD HH:mm:59"), //配送结束时间
        addedServices: this.getAddedServicesStr(),
        delivery: true,
      }
    },
    getAddedServicesStr() {
      return this.deliveryFrom.addedServices ? this.deliveryFrom.addedServices.join(',') : undefined
    },
    getAssigningList () { //已分配列表
      getOrderDeliveryInfoByDelivery(this.getOrderDeliveryInfoByDeliveryParams()).then(response => {
        response.data.data.map((item, index) => {
          item['id'] = index
        })
        this.AssigningData = response.data.data
      })
    },
    getEveryAreaDeliveryNumList () { //获取配送分配页面总仓和分仓的数据
      // console.log('获取配送分配页面总仓和分仓的数据','getEveryAreaDeliveryNumList')
      getEveryAreaDeliveryNum(this.getEveryAreaDeliveryNumParams()).then(res => {
        this.DistributionList = res.data.data
      })
    },
    handleFilter (times) { //查询
      this.deliveryFrom.page = 1
      this.deliveryFrom.totalWarehouseId = this.mainWarehouseIds

      var time1 = Date.parse(this.dayjs(times[0]).format("YYYY-MM-DD HH:mm:00"))
      var time2 = Date.parse(this.dayjs(times[1]).format("YYYY-MM-DD HH:mm:59"))
      //讲两个时间相减，求出相隔的天数
      var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24
      if (dayCount > 1) {
        this.$message({
          showClose: true,
          message: "时间间隔不可超过1天",
          type: "warning"
        })
      } else {
        // console.log('deliveryFrom',this.deliveryFrom)
        this.indexs = '0'
        this.loadData()
      }
    },
    handleSetOutOrder (item) { //配送出发
      deliverySetOutOrder({
        orderIds: [item.id]
      }).then(res => {
        this.$message({
          type: "success",
          message: '订单配送出发成功'
        })
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)

      })
    },
    handleSelectionChange (item) { // 已分配多选
      let selParentItem = []
      item.forEach(selChild => {
        this.AssigningData.forEach(parent => {
          parent.list.forEach(child => {
            if (selChild.id === child.id) {
              selParentItem = parent
            }
          })
        })
      })
      const {
        id = null
      } = selParentItem
      this.multipleSelections[`multipleSelection${id}`] = item
      this.multipleSelection = this.multipleSelections[`multipleSelection${id}`]
    },
    handleSelectionChangeNo (item) { //未分配多选
      this.multipleSelectionNo = item
    },
    clearOtherNo () { //清除已分配数据
      this.AssigningData.map((item, index) => {
        this.$refs[`multipleTable${index}`][0].clearSelection()
      })
      this.multipleSelection = []
    },
    clearOther (item) { //清除未分配数据
      this.$refs.multipleTableNo.clearSelection()
      const {
        id
      } = item
      const noSel = this.AssigningData.filter(parent => parent.id !== id)
      noSel.forEach(item => {
        this.$refs[`multipleTable${item.id}`][0].clearSelection()
        this.multipleSelections[`multipleSelection${item.id}`] = []
      })

    },
    handleAllSetOutOrder (item) { //批量配送出发
      var SetOutOrderIds = []
      const {
        id
      } = item

      if (this.multipleSelection && this.multipleSelection.length >
        0 && this.multipleSelections[`multipleSelection${id}`] && this.multipleSelections[`multipleSelection${id}`].length >
        0) {
        this.multipleSelection.map(item => {
          SetOutOrderIds.push(item.id)
        })

        deliverySetOutOrder({
          orderIds: SetOutOrderIds
        }).then(res => {
          this.$message({
            type: "success",
            message: '订单配送出发成功'
          })
          setTimeout(() => {
            this.loadData()
          }, 1.5 * 1000)
        })

      } else {
        this.$message.warning("请选择至少一张订单")
        return
      }
    },
    // 公共模块------------------------------------------------------------------------------------------------------
    mainWarehouse () { // 地区列表
      getMainWarehouseListAll({
        parentId: this.cityareaId
      }).then(response => {
        response.data.data.unshift({
          id: '',
          deptName: "全部"
        })
        this.mainWarehousesList = response.data.data
        this.mainWarehouseIds = response.data.data[0].id
        this.mainWarehouseNames = response.data.data[0].deptName
        this.deliveryFrom.totalWarehouseId = response.data.data[0].id
      })
    },
    // 地区选中事件
    getmainWarehouseIds (data) {
      this.deliveryFrom.totalWarehouseId = data.value
      if (this.mainWarehouseNames == '全部') {
        this.mainWarehouseNames = ''
        this.mainWarehouseIds = data.value
      } else {
        this.mainWarehouseNames = data.label
        this.mainWarehouseIds = data.value
        this.barnchWarehousesName = '全部'
      }
      this.deliveryFrom.warehouseId = ""
    },
    // 区域及分仓数据切换
    handleTabs (index, item) {
      // console.log(item, item.mainWarehouseId)
      this.indexs = index
      if (this.mainWarehouseNames == '全部' || this.mainWarehouseNames == '') {
        this.warehouseId = item.warehouseId
      }
      this.deliveryFrom.totalWarehouseId = item.mainWarehouseId
      this.deliveryFrom.warehouseId = item.warehouseId
      this.loadData()
    },

    //查看订单------------------------------------------------------------------------------------------------
    handleWatchOrder (row) {
      this.activeName = 'first'
      this.reverse = false
      this.listdetails = Object.assign({}, row) // copy obj
      this.dialogorderdetail = true
      this.$refs.viewReceiverPhone && this.$refs.viewReceiverPhone.init()
      getOrderInfo({
        orderId: this.listdetails.id
      }).then(res => {
        this.orderInfoList = res.data.data
      })
    },
    // 我的配送订单查看切换
    handleClick (tab) {
      if (tab.index == "0") {
        getOrderInfo({
          orderId: this.listdetails.id
        }).then(res => {
          this.orderInfoList = res.data.data
        })
      } else if (tab.index == "1") {
        getOrderGoodsInfo({
          orderId: this.listdetails.id
        }).then(res => {
          this.goodInfoData = res.data.data
          var goodInfototal = []
          this.goodInfoData.map(item => {
            goodInfototal.push(item.totalPrice)
          })
          goodInfototal.reduce(function (total, currentValue) {
            goodInfototal = total + currentValue
            return goodInfototal
          })
          this.goodInfototal = goodInfototal / 100
        })
      } else if (tab.index == "2") {
        getOrderInfo({
          orderId: this.listdetails.id
        }).then(res => {
          this.$nextTick(() => {
            this.$refs.xmMap.clearMap()
            this.addMarker();
          })
        })
      } else if (tab.index == "3") {
        getOrderOperateLog({
          orderId: this.listdetails.id
        }).then(res => {
          this.activities = res.data.data
        })
      }
    },
    //地图锚点
    addMarker () {
      const marker = this.$refs.xmMap.createMarker({
        longitude: this.orderInfoList.longitude,
        latitude: this.orderInfoList.latitude,
        label: {
          content: `<div class='info'>${this.orderInfoList.receiverAddress}</div>`
        },
      })
      this.$refs.xmMap.map.add([marker])
      this.$refs.xmMap.setZoomAndCenter(13, [this.orderInfoList.longitude, this.orderInfoList.latitude])
    },
    // 异常列表数据------------------------------------------------------------------------
    getabnormalList () {
      this.abnormalFrom.deptId = this.cityareaId
      this.abnormalFrom.deliveryStartTime = this.timeValue[0] + ":00"
      this.abnormalFrom.deliveryEndTime = this.timeValue[1] + ":59"
      // console.log('this.abnormalFrom',this.abnormalFrom)
      getOrderDeliveryAbnormalList(this.abnormalFrom).then(res => {
        this.abnormalList = res.data.data.rows
        this.abnormatotal = res.data.data.total
      })
    },
    HandledeliveryAbnormal () {
      this.showdelivery = false
      this.showabnormal = true
      this.getabnormalList()
    },
    handleabnormalFilter () {
      this.getabnormalList()
    },
    backabnormal () {
      this.showdelivery = true
      this.showabnormal = false
    },
    // 驳回按钮
    handleturndown (item) {
      this.dialogturndownVisible = true
      this.rejectOrderDeliveryAbnormalId = item.id
    },
    // 确定驳回页面
    submitturndownform (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const rejectData = {
            id: this.rejectOrderDeliveryAbnormalId,
            reason: this.turndownform.reason
          }
          this.$confirm("确定要把该异常配送订单驳回？ 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              rejectOrderDeliveryAbnormal(rejectData).then(res => {
                this.$message({
                  type: "success",
                  message: "该异常配送订单处理完成!"
                })
                this.dialogturndownVisible = false
                this.getabnormalList()

              })
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消驳回处理"
              })
            })

          // alert('submit!');
        } else {
          return false
        }
      })
    },
    clickFraming (val) { //开启刷单
      window.clearInterval(this.clickfarmingTimer)
      if (val == true) {
        this.loadData()
        this.clickfarmingTimer = setInterval(() => {
          this.loadData()
        }, 600 * 1000)
      } else {
        window.clearInterval(this.clickfarmingTimer)
      }
    },
    // 选择配送员-------------------------------------------------------------------------------------
    handledistror (sel, list) {
      this.saveflag = false
      for (let warp in list) {
        list[warp].map(item => {
          item.isSelected = 0
          if (sel.name === item.name) {
            item.isSelected = 1
          }
        })
      }
      this.delivery = sel.name
    },
    // 清空配送员
    handledeliverys (list) {
      this.saveflag = true
      for (let warp in list) {
        list[warp].map(item => {
          item.isSelected = 0
        })
      }
      this.delivery = ''
    },
    handelsaveOrdernoraml () {
      const selectData = {
        id: this.deliveriesId,
        delivery: this.delivery
      }
      this.distributing = true
      modifyOrderDeliveryAbnormal(selectData).then(() => {
        this.$notify({
          title: '提示',
          message: '该订单的配送员已清空',
          type: 'warning'
        })
        this.dialogDistributorVisible = false
        this.dialogDistributorVisibles = false
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)
      }).finally(() => {
        this.distributing = false
      })

    },

    handelsaveOrder () {
      let ids = []
      this.multipleSelection.map(item => {
        ids.push(item.id)
      })
      const selectData = {
        ids: ids,
        account: this.delivery
      }
      this.distributing = true
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: '提示',
          message: '该订单的配送员已清空',
          type: 'warning'
        })
        this.dialogDistributorVisible = false
        this.dialogDistributorVisibles = false
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)
      }).finally(() => {
        this.distributing = false;
      });
    },
    handelsaveOrderno () { //清空配送员保存
      let ids = []
      this.multipleSelectionNo.map(item => {
        ids.push(item.id)
      })
      const selectData = {
        ids: ids,
        account: this.delivery
      }
      this.distributing = true
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: '提示',
          message: '该订单的配送员已清空',
          type: 'warning'
        })
        this.dialogDistributorVisible = false
        this.dialogDistributorVisibles = false
        this.dialogDistributorVisibleno = false
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)
      }).finally(() => {
        this.distributing = false;
      });
    },
    handleTransferpre (item) {
      this.dialoghandleReturnferVisible = true
      this.rejectOrderDeliveryAbnormalId = item.id
    },
    handleTransfer () { //转给客服
      let id = this.rejectOrderDeliveryAbnormalId
      let content = this.turndownform.reason
      this.$confirm("把订单交给客服处理？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          turnWorkOrderDeliveryAbnormal({
            id: id,
            content: content
          }).then(
            () => {
              this.$message({
                type: "success",
                message: "已转到异常工单!"
              })
              this.turndownform.reason = ''
              this.dialoghandleReturnferVisible = false
              this.getabnormalList()
            }
          )
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消转给客服处理"
          })
        })
    },
    handleModifydelivery (item) { //配送异常列表
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let item = this.multipleSelection[i]
        if (this.delivery.indexof() > -1) {
          this.$message.warning("京东物流订单需要取消后才能修改配送员")
          return
        }
      }
      this.deliveriesId = item.id
      //修改配送员
      this.dialogDistributorVisible = true
      let ids = []
      this.multipleSelection.map(item => {
        ids.push(item.xmbzNo)
      })
      const selectData = {
        xmbzNos: item.xmbzNo,
        deptId: this.cityareaId
      }
      getdeliveriesList(selectData).then(response => {
        this.deliveriesList = response.data.data
        let isSelectedlist = []
        for (let warp in this.deliveriesList) {
          this.deliveriesList[warp].map(item => {
            if (item.isSelected == '1') {
              isSelectedlist.push(item)
            }
          })
        }
        if (isSelectedlist.length > 0) {
          this.saveflag = false
        } else {
          this.saveflag = true
        }
      })
    },
    handleModifydeliverysUn () { //未分配修改配送员
      if (this.multipleSelectionNo.length === 0) {
        this.$message.warning("请选择至少一张订单")
        return
      } else {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          let item = this.multipleSelection[i]
          if (this.delivery.indexof() > -1) {
            this.$message.warning("京东物流订单需要取消后才能修改配送员")
            return
          }
        }
        this.dialogDistributorVisibleno = true
        let ids = []
        this.multipleSelectionNo.map(item => {
          ids.push(item.xmbzNo)
        })
        const selectData = {
          xmbzNos: ids.join(','),
          deptId: this.cityareaId
        }
        getdeliveriesList(selectData).then(response => {
          this.deliveriesList = response.data.data
          let isSelectedlist = []
          for (let warp in this.deliveriesList) {
            this.deliveriesList[warp].map(item => {
              if (item.isSelected == '1') {
                isSelectedlist.push(item)
              }
            })
          }
          if (isSelectedlist.length > 0) {
            this.saveflag = false
          } else {
            this.saveflag = true
          }
        })
      }
    },
    handleModifydeliverys (item) {// 已分配
      let delivery = this.delivery.indexOf()
      if (delivery > -1) {
        this.$message.warning("京东物流订单需要取消后才能修改配送员")
        return
      }
      const {
        id
      } = item
      if (this.$refs[`multipleTable${id}`][0].selection.length > 0) {
        this.dialogDistributorVisibles = true
        let ids = []
        this.multipleSelections[`multipleSelection${id}`].map(item => {
          ids.push(item.xmbzNo)
        })
        const selectData = {
          xmbzNos: ids.join(','),
          deptId: this.cityareaId
        }
        getdeliveriesList(selectData).then(response => {
          this.deliveriesList = response.data.data
          let isSelectedlist = []
          for (let warp in this.deliveriesList) {
            this.deliveriesList[warp].map(item => {
              if (item.isSelected == '1') {
                isSelectedlist.push(item)
              }
            })
          }
          if (isSelectedlist.length > 0) {
            this.saveflag = false
          } else {
            this.saveflag = true
          }
        })

      } else {
        this.$message.warning("请选择至少一张订单")
        return
      }

    },

    handleSelectionNoChange (val) {
      this.multipleSelection = val
      // this.
    },
    // 配送分配的修改配送员
    handelDistributeDeliveryOrder (list) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择至少一张订单")
        return
      }
      let isSelectedlist = []
      for (let warp in list) {
        list[warp].map(item => {
          if (item.isSelected == '1') {
            isSelectedlist.push(item)
          }
        })
      }
      if (isSelectedlist.length > 1) {
        this.$message.warning("不能同时分配给多个配送员")
        return
      }
      let ids = []
      this.multipleSelection.map(item => {
        ids.push(item.id)
      })
      const selectData = {
        ids: ids,
        account: this.delivery == '' ? isSelectedlist[0].name : this.delivery
      }
      this.distributing = true
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: "成功",
          message: "修改配送员成功",
          type: "success",
          duration: 2000
        })
        this.dialogDistributorVisibles = false
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)
      }).finally(() => {
        this.distributing = false
      })
    },

    handelDistributeDeliveryOrderno (list) {
      if (this.multipleSelectionNo.length === 0) {
        this.$message.warning("请选择至少一张订单")
        return
      }
      let isSelectedlist = []
      for (let warp in list) {
        list[warp].map(item => {
          if (item.isSelected == '1') {
            isSelectedlist.push(item)
          }
        })
      }
      if (isSelectedlist.length > 1) {
        this.$message.warning("不能同时分配给多个配送员")
        return
      }
      let ids = []
      this.multipleSelectionNo.map(item => {
        ids.push(item.id)
      })
      const selectData = {
        ids: ids,
        account: this.delivery == '' ? isSelectedlist[0].name : this.delivery
      }
      this.distributing = true
      distributeDeliveryForOrderDispatch(selectData).then(() => {
        this.$notify({
          title: "成功",
          message: "修改配送员成功",
          type: "success",
          duration: 2000
        })
        this.dialogDistributorVisibleno = false
        setTimeout(() => {
          this.loadData()
        }, 1.5 * 1000)
      }).finally(() => {
        this.distributing = false
      })
    },
    handelDistributeDeliveryForOrder (list) {
      let isSelectedlist = []
      for (let warp in list) {
        list[warp].map(item => {
          if (item.isSelected == '1') {
            isSelectedlist.push(item)
          }
        })
      }
      if (isSelectedlist.length > 1) {
        this.$message.warning("不能同时分配给多个配送员")
        return
      }
      const deliveryData = {
        id: this.deliveriesId,
        delivery: this.delivery == '' ? isSelectedlist[0].name : this.delivery
      }
      this.distributing = true
      modifyOrderDeliveryAbnormal(deliveryData).then((res) => {
        if (res.data.code == 200) {
          this.$notify({
            title: "成功",
            message: "修改配送员成功",
            type: "success",
            duration: 2000
          })
          this.dialogDistributorVisible = false
          this.getabnormalList()
        }
      }).finally(() => {
        this.distributing = false
      })
    }
  }
};
</script>
<style lang="scss">
.app-container-delivery {

  table tr,
  table tr td {
    border-right: none !important;
  }

  .maindelivery {
    .delivery-container {
      .flexmaindelivery {
        display: flex;
        display: flex;
        flex-wrap: wrap;

        // .formitem {
        //   width: 640px;
        // }
      }

      .el-form-item {
        margin-bottom: 10px !important;
      }
    }

    .Distribution {
      display: flex;
      margin-bottom: 20px;
      cursor: pointer;
      flex-wrap: wrap;

      .Distribution-item {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        border-radius: 4px;
        border: 1px solid #ebeef5;
        background-color: #fff;
        overflow: hidden;
        color: #606266;
        -webkit-transition: 0.3s;
        transition: 0.3s;
        margin-bottom: 5px;
        padding: 3px;
        margin-right: 4px;
        text-align: center;
        box-sizing: border-box;

        .Warehouse {
          border-bottom: 1px solid #cccccc;
          height: 24px;
        }

        .deliveryData {
          // display: flex;
          text-align: center;
          // justify-content: space-between;

          .Unassigned {
            display: flex;
            line-height: 24px;
            justify-content: space-around;

            .names {
              margin-right: 8px;
            }
          }

          .allocated {
            line-height: 24px;
            display: flex;
            justify-content: space-around;
            border-top: 1px solid #cccccc;
          }
        }

        &.active {
          // font-size: 20px;
          color: #fff;
          background: #43a0ff;
          // border-bottom: 1px solid #43a0ff;
        }
      }

      .delivery-Abnormal {
        display: flex;
        align-items: center;
      }
    }

    .DistributionTable {
      img {
        width: 20px;
        height: 20px;
        vertical-align: middle;
        margin-right: 10px;
      }

      .unassignedList {
        margin-bottom: 20px;

        .tag {
          line-height: 24px;
          margin-bottom: 10px;
          display: flex;

          .ordernum {
            .order-quantity {
              font-size: 14px;
              color: #707275;
              line-height: 24px;
            }
          }
        }
      }

      .assigning {
        margin-bottom: 20px;

        .tag {
          line-height: 24px;
          margin-bottom: 10px;
          display: flex;
          font-size: 14px;

          .ordernum {
            margin-right: 15px;

            .delivery {
              color: #707275;
            }

            .order-quantity {
              color: #f76234;
            }

            .order-signfor {
              color: #77b714;
            }
          }
        }
      }
    }
  }

  .orderInfo {
    .orderInfo-item {
      display: flex;
      line-height: 40px;
      display: flex;
      color: #8c8989;

      .name {
        display: block;
        width: 120px;
        color: #000;
      }
    }
  }

  .goodInfo {
    .goodInfomain {
      webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      border: 1px solid #ebeef5;
      background-color: #fff;
      overflow: hidden;
      color: #606266;
      transition: 0.3s;
      margin-bottom: 10px;
      padding: 10px;

      .goodInfo-item {
        display: flex;
        line-height: 24px;

        .name {
          display: block;
          color: #000;
        }
      }
    }

    .goodInfototal {
      font-weight: 500;
      font-size: 18px;
    }
  }

  .showabnormal {
    .fifterabnormal {
      .flexmaindelivery {
        display: flex;

        .formitem {
          width: 640px;
        }
      }

      .el-form-item {
        margin-bottom: 10px !important;
      }
    }

    .tab {
      display: flex;
      margin-bottom: 10px;
      cursor: pointer;

      .tab-item {
        color: #cccccc;
      }

      .tab-item.act {
        color: #000;
      }
    }

    .abnormaList {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      border: 1px solid #ebeef5;
      background-color: #fff;
      overflow: hidden;
      color: #606266;
      -webkit-transition: 0.3s;
      transition: 0.3s;
      margin-bottom: 10px;

      .line {
        display: flex;
        line-height: 40px;

        .xmbzNo {
          padding-left: 20px;
          padding-right: 100px;
          color: #000;
          width: 400px;
        }

        .count {
          color: #ff0000;
        }
      }

      .abnormaList-item {
        border-top: 1px solid #cccccc;
        padding: 10px 10px 0;

        .flexabnorma {
          display: flex;
          line-height: 30px;

          em {
            font-style: normal;
            padding: 0 5px;
          }

          p {
            padding: 0;
            margin: 0;
            width: 15%;

            em {
              font-style: normal;
              padding: 0 5px;
            }
          }
        }
      }

      .deliveryflex {
        padding: 0 10px 10px;
        display: flex;
        justify-content: space-around;
        width: 300px;
        float: right;
      }
    }

    .abnormaListno {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      border: 1px solid #ebeef5;
      background-color: #fff;
      overflow: hidden;
      color: #606266;
      -webkit-transition: 0.3s;
      transition: 0.3s;
      margin-bottom: 10px;
      padding: 20px;
      text-align: center;
    }
  }

  .deliveriesList {
    border-top: 1px solid #ebeef5;
    display: flex;
    line-height: 44px;

    .deliveryperson {
      margin-right: 10px;
    }

    .delivery-item {
      cursor: pointer;
      display: flex;
      flex: 1;
      width: 50%;
      flex-wrap: wrap;

      span {
        width: 90px;

        text-align: center;

        &.active {
          width: 77px;
          height: 32px;
          line-height: 17px;
          border-radius: 3px;
          background-color: rgba(238, 248, 232, 1);
          color: rgba(122, 199, 86, 1);
          font-size: 12px;
          text-align: left;
          font-family: Roboto;
          border: 1px solid rgba(122, 199, 86, 1);
          text-align: center;
          line-height: 32px;
          margin-top: 6px;
        }
      }
    }

    &:last-child {
      border-bottom: 1px solid #ebeef5;
    }
  }
}
</style>
